package com.wyd.wenyongdaAdmin.admin.login.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wyd.wenyongdaAdmin.commons.model.admin.user.entity.UserAccountEntity;
import com.wyd.wenyongdaAdmin.commons.model.admin.user.vo.UserAccountVO;
import com.wyd.wenyongdaAdmin.commons.util.ApplicationContextUtil;
import com.wyd.wenyongdaAdmin.commons.util.ResultEnum;
import com.wyd.wenyongdaAdmin.commons.util.ResultUtil;
import com.wyd.wenyongdaAdmin.xo.admin.user.service.IUserAccountService;
import com.wyd.wenyongdaAdmin.xo.admin.user.service.IUserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "登录登出管理")
@Controller
@RequestMapping("/login")
@RefreshScope
public class LoginController {

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    private IUserAccountService userAccountService;

    private IUserInfoService userInfoService;

    @Autowired
    LoginController(IUserAccountService userAccountService, IUserInfoService userInfoService) {
        this.userAccountService = userAccountService;
        this.userInfoService = userInfoService;
    }



    @ApiOperation("登录")
    @PostMapping("/login")
    @ResponseBody
    public ResultUtil login(@RequestBody Map<String, Object> reqParams) {
        String username = (String) reqParams.get("username");
        String password = (String) reqParams.get("password");
        String code = (String) reqParams.get("code");
        if (StrUtil.isBlank(code)) {
            return ResultUtil.error(ResultEnum.VERIFY_CODE_IS_EMPTY);
        }
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBean("myRedisTemplate");
        if (code.equalsIgnoreCase(redisTemplate.opsForValue().get("verifyCode").toString())) {
            log.info("当前登录用户用户名为---" + username);
            UserAccountVO user = userAccountService.verifyLoginUserAccount(new UserAccountVO().setUsername(username));
            if(ObjectUtil.isNotNull(user)){
                if(user.getPassword().equals(password)) {
                    if(user.getIsEnabled() == 1) {
                        userAccountService.update(new UpdateWrapper<UserAccountEntity>().set("last_login", DateTime.now())
                                .eq("id", user.getId()));
                        return ResultUtil.ok().data("userInfo", user).data("token", JWTUtil.createToken(new HashMap<String, Object>() {
                            {
                                put("uuid", user.getId());
                            }
                        },"1234".getBytes()));
                    } else {
                        return ResultUtil.error(ResultEnum.USER_ACCOUNT_IS_DISABLED);
                    }

                } else {
                    return ResultUtil.error(ResultEnum.PASSWORD_ERROR);
                }
            }else {
                return ResultUtil.error(ResultEnum.USERNAME_ERROR_OR_UNKNOWN);
            }
        } else {
            return ResultUtil.error(ResultEnum.VERIFY_CODE_ERROR);
        }

    }




    @GetMapping("verifyCode/generateCode")
    public void generateCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        // 重新生成code
        lineCaptcha.createCode();
        final OutputStream outputStream = response.getOutputStream();
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBean("myRedisTemplate");
        redisTemplate.opsForValue().set("verifyCode", lineCaptcha.getCode(),30, TimeUnit.MINUTES);
        // 写出到浏览器（Servlet输出）
        lineCaptcha.write(outputStream);
        outputStream.close();
    }


}
